package com.lixin.smartclassroom.ui.home.tab2.activity

import android.graphics.Color
import android.view.View
import android.widget.CompoundButton
import android.widget.CompoundButton.OnCheckedChangeListener
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.drake.channel.sendEvent
import com.drake.net.utils.scopeDialog
import com.drake.net.utils.scopeNetLife
import com.drake.tooltip.dialog.BubbleDialog
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.api.addbigzhangjie
import com.lixin.smartclassroom.api.gettianshu
import com.lixin.smartclassroom.api.updatebigzhangjie
import com.lixin.smartclassroom.api.yanxuecoursedetail
import com.lixin.smartclassroom.bean.BaseBean
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.bean.ProgressBean
import com.lixin.smartclassroom.databinding.ActivityAddChapterBinding
import com.lixin.smartclassroom.ui.home.adapter.oneText
import com.lixin.smartclassroom.utils.NumberFormatUtil
import com.lixinkeji.base.BaseActivity
import com.lixinkeji.extension.dp2px
import com.lixinkeji.extension.getIntentBoolean
import com.lixinkeji.extension.getIntentSerializable
import com.lixinkeji.extension.getIntentString
import com.lixinkeji.extension.gone
import com.lixinkeji.extension.loadRound
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.parse
import com.lixinkeji.extension.setRoundRectBg
import com.lixinkeji.extension.start
import com.lixinkeji.extension.text
import com.lixinkeji.extension.toast
import com.lixinkeji.extension.visible
import com.lixinkeji.utils.StringUtil
import com.luck.picture.lib.entity.LocalMedia
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * Description 添加大章节
 * Author: lwc
 * Date:2023/12/8 14:56
 */
class AddChapterAct : BaseActivity<ActivityAddChapterBinding>() {
    override fun getViewBinding() = ActivityAddChapterBinding.inflate(layoutInflater)

    override fun topBarHide() = false
    override fun startPadding() = true

    private var taskType = ""
    private var courseid = ""
    private var ifSee = "2"//是否可见  1是  2否
    private var isEdit = false
    private var dataListBean: DataListBean? = null
    private var courseStartTime = ""

    private val progressList: MutableList<String> = mutableListOf()
    private val progressListProgressBean: MutableList<ProgressBean> = mutableListOf()
    private var selectPosition = -1

    override fun title(): String {
        isEdit = getIntentBoolean("isEdit")
        return if (isEdit) "编辑章节"
        else "添加章节"
    }

    override fun iniView() {
        taskType = getIntentString("type")
        courseid = getIntentString("courseid")

        if (isEdit) {
            dataListBean = getIntentSerializable("dataListBean")
            setUi()
        }
        binding.apply {
            btnAddContinue.setRoundRectBg(Color.parseColor("#E2E7FF"), dp2px(25f).toInt())
            when (taskType) {
                "3" -> {
                    llYanxue.visible()
                    llIfUserShow.gone()
                    getProgressData()
                    getYanXueDetailData()
                }
            }
        }
    }

    private fun getYanXueDetailData() {
        scopeNetLife {
            val baseBean = yanxuecoursedetail(courseid)
            if (baseBean.result == "0") {
                courseStartTime = baseBean.begintime.toString()
            } else {
                toast(baseBean.resultNote.toString())
            }
        }
    }

    private fun getProgressData() {
        scopeNetLife {
            val baseBean = gettianshu()
            if (baseBean?.result == "0") {
                for (i in 0 until baseBean.data?.size!!) {
                    progressList.add(baseBean.data!![i].name!!)
                    progressListProgressBean.add(baseBean.data!![i])
                }
            }
        }
    }

    private fun setUi() {
        binding.apply {
            btnAddContinue.gone()
            etTitle.setText(dataListBean?.title)
            switchIfSee.isSelected = dataListBean?.state == "1"
            ifSee = dataListBean?.state!!
            courseid = dataListBean?.id!!
            tvJindu.text = dataListBean?.jindu
            tvBeginTime.text = dataListBean?.begintime
        }

    }


    override fun onClick() {
        binding.apply {
            btnAddContinue.onClick {
                scopeNetLife {
                    when (taskType) {
                        "3" -> {

                            for (i in 0 until progressListProgressBean.size) {
                                if (progressListProgressBean[i].name == tvJindu.text) {
                                    selectPosition = i
                                }
                            }
                            val baseBean = addbigzhangjie(
                                etTitle.text(),
                                "1",
                                courseid,
                                taskType,
                                progressListProgressBean[selectPosition].id,
                                tvBeginTime.text.toString()
                            )
                            if (baseBean.result == "0") {
                                goAddSmallChapter(baseBean)

                            }
                        }

                        else -> {
                            val baseBean =
                                addbigzhangjie(etTitle.text(), ifSee, courseid, taskType)
                            if (baseBean.result == "0") {
                                goAddSmallChapter(baseBean)
                            }

                        }
                    }


                }
            }
            btnSave.onClick {
                if (!isEdit) {
                    val bubbleDialog = BubbleDialog(this@AddChapterAct)
                    scopeDialog(bubbleDialog) {
                        when (taskType) {
                            "3" -> {

                                if (tvJindu.text == "请选择活动进度") {
                                    toast("请选择活动进度")
                                    return@scopeDialog
                                }

                                for (i in 0 until progressListProgressBean.size) {
                                    if (progressListProgressBean[i].name == tvJindu.text) {
                                        selectPosition = i
                                    }
                                }

                                addbigzhangjie(
                                    etTitle.text(),
                                    "1",
                                    courseid,
                                    taskType,
                                    progressListProgressBean[selectPosition].id,
                                    tvBeginTime.text.toString()
                                )
                            }

                            else -> addbigzhangjie(etTitle.text(), ifSee, courseid, taskType)
                        }

                        sendEvent("cs", "refreshDaGang")
                        finish()
                    }
                } else {
                    val bubbleDialog = BubbleDialog(this@AddChapterAct)
                    scopeDialog(bubbleDialog){
                        when (taskType) {
                            "3" -> {
                                if (tvJindu.text == "请选择活动进度") {
                                    toast("请选择活动进度")
                                    return@scopeDialog
                                }
                                updatebigzhangjie(
                                    etTitle.text(),
                                    "1",
                                    courseid,
                                    progressListProgressBean[selectPosition].id,
                                    tvBeginTime.text.toString()
                                )
                            }

                            else -> updatebigzhangjie(etTitle.text(), ifSee, courseid)
                        }

                        sendEvent("cs", "refreshDaGang")
                        finish()
                    }
                }

            }

            btnChangeStartTime.onClick {
                chooseDate(
                    "选择开始时间",
                    binding.tvBeginTime.text.toString(),
                    binding.tvBeginTime
                )
            }

            btnChangeProgress.onClick {
                chooseSingleWithSlideUp(
                    "请选择活动进度",
                    progressList,
                    tvJindu.text.toString(),
                    tvJindu
                )
            }

            switchIfSee.setOnCheckedChangeListener { _, isChecked ->
                ifSee = if (isChecked) {
                    "1"
                } else {
                    "2"
                }
            }
        }
    }

    private fun goAddSmallChapter(baseBean: BaseBean) {
        sendEvent("cs", "refreshDaGang")
        start(AddSmallChapterAct::class.java) {
            putExtra("type", taskType)
            putExtra("bigzjid", baseBean.id)
        }
        finish()
    }

    private fun chooseDate(title: String, def: String, view: TextView) {
        val format = "yyyy-MM-dd HH:mm"
        val selectedDate = Calendar.getInstance()
        if (def.isNotEmpty() && def != "选择开始时间") {
            val df: DateFormat = SimpleDateFormat(format, Locale.getDefault())
            selectedDate.time = df.parse(def)
        }

        val startDate = Calendar.getInstance()
        val endDate = Calendar.getInstance()

        startDate.time = courseStartTime.parse(format)
        startDate.add(Calendar.DAY_OF_YEAR, 1);


        endDate.set(
            endDate.get(Calendar.YEAR) + 1,
            12,
            endDate.get(Calendar.DAY_OF_MONTH),
            endDate.get(Calendar.HOUR),
            endDate.get(Calendar.MINUTE),
            endDate.get(Calendar.SECOND)
        )

        val mDatePickerView = TimePickerBuilder(this, object : OnTimeSelectListener {
            override fun onTimeSelect(date: Date?, v: View?) {
                val df: DateFormat = SimpleDateFormat(format, Locale.getDefault())
                val time = df.format(date)
                view.text = time
            }
        })
        mDatePickerView.addOnCancelClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                view.text = "选择开始时间"
            }
        })
        val mDatePickerViewBuilder =
            mDatePickerView.setType(booleanArrayOf(true, true, true, true, true, false))// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(16)//滚轮文字大小
                .setTitleSize(15)//标题文字大小
                .setTitleText(title)//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(ContextCompat.getColor(this, R.color.color_blue_44))//确定按钮文字颜色
                .setCancelColor(ContextCompat.getColor(this, R.color.color_blue_44))//取消按钮文字颜色
                .setTitleColor(ContextCompat.getColor(this, R.color.color_black_33))
                .setTitleBgColor(Color.WHITE)//标题背景颜色
                .setBgColor(Color.WHITE)//滚轮背景颜色
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)
                .setLineSpacingMultiplier(2.5f)
                .setLabel("", "", "", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build()

        if (!mDatePickerViewBuilder.isShowing) mDatePickerViewBuilder.show()
    }

    /**
     * 选择可见范围
     * */
    private fun chooseSingleWithSlideUp(
        title: String,
        list: MutableList<String>,
        def: String,
        view: TextView
    ) {
        var currentIndex =
            if (!StringUtil.isEmpty(def) && ("请选择活动进度" != def)) {
                list.indices.find {
                    def == list[it]
                }
            } else {
                0
            }
        if (currentIndex == null) {
            currentIndex = 0
        }

        val mSinglePop: OptionsPickerView<Any> =
            OptionsPickerBuilder(this) { options1, _, _, _ ->
                view.text = list[options1]
            }
                .setTitleText(title)
                .setTitleSize(15)
                .setSubCalSize(15)//确定和取消文字大小
                .setSubmitColor(Color.parseColor("#4495FE"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#4495FE"))//取消按钮文字颜色
                .setTitleColor(ContextCompat.getColor(this, R.color.color_black_33))
                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
                .setContentTextSize(16)//滚轮文字大小
                .isRestoreItem(false)//切换时是否还原，设置默认选中第一项。
                .setSelectOptions(currentIndex, 0, 0)
                .setLineSpacingMultiplier(2.3f)
                .isDialog(false)//是否显示为对话框样式
                .build()
        mSinglePop.setNPicker(list as List<Any>?, null, null)
        if (!mSinglePop.isShowing) mSinglePop.show()
    }
}